{% extends 'user/base.html' %}
{% block title %}
    <title>文章页面</title>
{% endblock %}

{% block extendcss %}
<!-- navbar透明 -->
    {# 引入 GitHub Markdown 样式 #}
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.1.0/github-markdown.min.css">
    <style>
        .navbar {
        position: fixed;
        top: 0;
        width: 100%;
        background-color: rgba(255, 255, 255, 0.7) !important; /* 半透明背景 */
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10;
        backdrop-filter: saturate(180%) blur(20px);
            border-bottom: #faf7f7 1px solid;
        }
        .markdown-body {
            box-sizing: border-box;
            min-width: 200px;
            max-width: 980px;
            margin: 0 auto;
            padding: 45px;
        }
    </style>

{% endblock %}
{% block content %}
<!-- Main content 主要内容---->
<section class="pt-lg-6 pl-md-5" data-aos="zoom-in">
    <div class="page-body pb-5">
        <div class="container-xl ">
            <!-- article 标题 -->
            <div class="row mb-2 text-center">
                <div class="col-lg-12">
                    <h2 class=" mt-4 badge-soft-success">{{ articles.title }}</h2>
                    <div class="mt-2">
                        <p class="lead lh-180">{{ articles.published_date }}----来源：{{ articles.user.username }}</p>
                    </div>
                </div>
            </div>
            <!-- article 内容 -->
            <div class="row justify-content-center">
                <div class="col-lg-10 col-xl-9">
                    <div class="card card-lg">
                        {# 文章展示模板 #}
                        <div class="markdown-body">
                            {{ articles.content|safe }}
                        </div>
                    </div>

                    <!-- 评论表单 -->
                    <div class="comment-section">
                    <h4>用户评论</h4>
                    <form id="articleCommentForm">
                        <textarea name="content" rows="3" required placeholder="写下你的评论..." class="form-control"></textarea>
                        <button type="submit" class="btn btn-sm btn-primary mt-2">提交评论</button>
                    </form>

                    <h5>全部评论 (<span id="articleCommentCount">{{ articles.comments|length }}</span>)</h5>
                    <ul class="comment-list" id="articleCommentList">
                        {% for comment in articles.comments %}
                            <li class="comment-item" id="article-comment-{{ comment.id }}">
                                <div class="comment-header">
                                    <strong>{{ comment.user.username }}{% if comment.user_id == session['user_id'] %}（我）{% endif %}</strong>
                                    <small class="text-muted">{{ comment.created_at.strftime('%Y-%m-%d %H:%M:%S') }}</small>
                                    {% if comment.user_id == session['user_id'] %}
                                        <button class="btn btn-link btn-sm text-danger delete-article-comment" data-id="{{ comment.id }}">删除</button>
                                    {% endif %}
                                </div>
                                <p class="comment-content">{{ comment.content }}</p>
                            </li>
                        {% endfor %}
                    </ul>
                </div>
                </div>
            </div>
        </div>
    </div>
</section>

{% if request.args.get('login_required') %}
<script>
    if (confirm('请先登录才能评论！')) {
        window.location.href = "{{ url_for('login.login', next=request.url) }}";
    }
</script>
{% endif %}

{% if request.args.get('deleted') %}
<script>
    alert('评论已删除！');
</script>
{% endif %}

{% if request.args.get('delete_failed') %}
<script>
    alert('无法删除评论！');
</script>
{% endif %}

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 处理文章评论提交
    document.getElementById('articleCommentForm').addEventListener('submit', function(event) {
        event.preventDefault();
        console.log('提交文章评论表单');
        const formData = new FormData(this);
        fetch("{{ url_for('story.add_article_comment', art_id=articles.id) }}", {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            console.log('提交文章评论响应:', data);
            if (data.success) {
                const commentList = document.getElementById('articleCommentList');
                const newComment = document.createElement('li');
                newComment.className = 'comment-item';
                newComment.id = `article-comment-${data.comment_id}`; // 确保id格式正确
                newComment.innerHTML = `
                    <div class="comment-header">
                        <strong>${data.username}（我）</strong>
                        <small class="text-muted">${data.created_at}</small>
                        <button class="btn btn-link btn-sm text-danger delete-article-comment" data-id="${data.comment_id}">删除</button>
                    </div>
                    <p class="comment-content">${data.content}</p>
                `;
                commentList.appendChild(newComment);
                document.getElementById('articleCommentCount').textContent = parseInt(document.getElementById('articleCommentCount').textContent) + 1;
                this.reset();

                // 显示提交成功提示信息
                const alertBox = document.createElement('div');
                alertBox.className = 'alert alert-success';
                alertBox.textContent = '评论提交成功！';
                alertBox.style.position = 'fixed';
                alertBox.style.top = '50%';
                alertBox.style.left = '50%';
                alertBox.style.transform = 'translate(-50%, -50%)';
                alertBox.style.zIndex = '1000';
                document.body.appendChild(alertBox);
                console.log('提交成功提示信息已显示');

                // 2秒后自动消失
                setTimeout(() => {
                    alertBox.remove();
                    console.log('提交成功提示信息已移除');
                }, 2000);
            } else {
                alert(data.message);
            }
        });
    });

    // 处理文章评论删除
    document.getElementById('articleCommentList').addEventListener('click', function(event) {
        if (event.target.classList.contains('delete-article-comment')) {
            const commentId = event.target.getAttribute('data-id');
            console.log('删除文章评论ID:', commentId);
            fetch(`{{ url_for('story.delete_article_comment', art_id=articles.id, comment_id=0) }}`.replace('0', commentId), {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                console.log('删除文章评论响应:', data);
                if (data.success) {
                    const commentItem = document.getElementById(`article-comment-${commentId}`);
                    console.log('删除文章评论响应commentItem:', commentItem);
                    if (commentItem) {
                        commentItem.remove();
                        document.getElementById('articleCommentCount').textContent = parseInt(document.getElementById('articleCommentCount').textContent) - 1;

                        // 显示删除成功提示信息
                        const alertBox = document.createElement('div');
                        alertBox.className = 'alert alert-danger';
                        alertBox.textContent = '评论删除成功！';
                        alertBox.style.position = 'fixed';
                        alertBox.style.top = '50%';
                        alertBox.style.left = '50%';
                        alertBox.style.transform = 'translate(-50%, -50%)';
                        alertBox.style.zIndex = '1000';
                        document.body.appendChild(alertBox);
                        console.log('删除成功提示信息已显示');

                        // 2秒后自动消失
                        setTimeout(() => {
                            alertBox.remove();
                            console.log('删除成功提示信息已移除');
                        }, 2000);
                    }
                } else {
                    alert(data.message);
                }
            });
        }
    });
});
</script>
{% endblock %}
{% block script %}
{% endblock %}